package Controller

import (
	"backend/Dao"
	"backend/Service/dbService"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type ChapterController struct {
}

type repAddNewChapter struct {
	ChapterName     string `json:"chapter_name"`
	ChapterSort     int    `json:"chapter_sort,string"`
	ChapterDescribe string `json:"chapter_describe"`
	ChapterData     string `json:"chapter_data"`
	CurriculumId    int    `json:"curriculum_id,string"`
}

func (this ChapterController) AddNewChapter(c *gin.Context) {
	var data = repAddNewChapter{}
	err := c.BindJSON(&data)
	if err != nil {
		fmt.Println("err", err)
	}
	c2 := &Dao.Chapter{
		Model:           Dao.GetModel(),
		ChapterName:     data.ChapterName,
		ChapterSort:     data.ChapterSort,
		ChapterDescribe: data.ChapterDescribe,
		ChapterData:     data.ChapterData,
		CurriculumId:    data.CurriculumId,
	}
	fmt.Println(data)
	dbService.DbConn.Transaction(func(tx *gorm.DB) error {
		if err = tx.Exec("update chapter set chapter_sort = chapter_sort+1 where chapter_sort >= ?", c2.ChapterSort).Error; err != nil {
			return err
		}
		if err = tx.Create(c2).Error; err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		c.JSON(500, err)
	}
	c.JSON(200, "ok")
}

type reqDelChapter struct {
	ID          uint `json:"ID,string"`
	ChapterSort int  `json:"ChapterSort,string"`
}

//
// DelChapter
// @Description: 删除章节,并将之后的章节sort-1
// @author MaTaoXun 2022-01-15 15:59:20
// @return gin.HandlerFunc
//
func (this ChapterController) DelChapter(c *gin.Context) {
	var data = reqDelChapter{}
	err := c.BindJSON(&data)
	if err != nil {
		fmt.Println("err", err)
	}
	dbService.DbConn.Exec("update chapter set chapter_sort = chapter_sort-1 where chapter_sort >= ?", data.ChapterSort)
	dbService.DbConn.Delete(&Dao.Chapter{}, data.ID)
	c.JSON(200, "ok")
}

type reqUpdateChapterData struct {
	ID          uint   `json:"id,string"`
	ChapterData string `json:"chapter_data"`
}

//
// UpdateChapterData
// @Description: 根据章节id更新章节数据
// @author MaTaoXun 2022-01-15 16:47:11
// @return gin.HandlerFunc
//
func (this ChapterController) UpdateChapterData(c *gin.Context) {
	var data = reqUpdateChapterData{}
	err := c.BindJSON(&data)
	Chapter := Dao.Chapter{
		Model: Dao.Model{
			ID: data.ID,
		},
	}
	dbService.DbConn.Model(&Chapter).Update("chapter_data", data.ChapterData)
	if err != nil {
		fmt.Println("err", err)
	}
	c.JSON(200, "ok")
}

type reqGetChapterByCurriculum struct {
	Id int `json:"id,string"`
}

//
// GetChapterByCurriculum
// @Description: 获取当前id课程下的章节
// @author MaTaoXun 2022-01-15 16:50:02
// @return gin.HandlerFunc
//
func (this ChapterController) GetChapterByCurriculum(c *gin.Context) {
	var data = reqGetChapterByCurriculum{}
	err := c.BindJSON(&data)
	var Chapter []Dao.Chapter
	dbService.DbConn.Where("curriculum_id = ?", data.Id).Order("chapter_sort").Find(&Chapter)
	if err != nil {
		fmt.Println("err", err)
	}
	c.JSON(200, Chapter)
}
